package com.zch.starter.sentinel.springboot.starter.filter;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.zch.starter.sentinel.springboot.starter.config.SentinelResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SentinelUrlBlockHandler implements UrlBlockHandler {

    public static void init() {
        WebCallbackManager.setUrlBlockHandler(new SentinelUrlBlockHandler());
    }

    private static final SentinelResult SENTINEL_RESULT = SentinelResult.rejectPass();

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        StringBuffer url = request.getRequestURL();
        if ("GET".equals(request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
            url.append("?").append(request.getQueryString());
        }

        if (StringUtil.isBlank(WebServletConfig.getBlockPage())) {
            writeDefaultBlockedPage(response, WebServletConfig.getBlockPageHttpStatus());
        } else {
            String redirectUrl = WebServletConfig.getBlockPage() + "?http_referer=" + url.toString();
            response.sendRedirect(redirectUrl);
        }
    }

    private static void writeDefaultBlockedPage(HttpServletResponse response, int httpStatus) throws IOException {
        response.setStatus(httpStatus);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try (PrintWriter out = response.getWriter()) {
            out.print(JSON.toJSONString(SENTINEL_RESULT));
            out.flush();
        }
    }

}
